package com.settlement.system.service.impl;

import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.settlement.system.mapper.BaseMapper;
import com.settlement.system.mapper.TblQueryFieldConfigMapper;
import com.settlement.system.common.enums.ReturnStatusEnum;
import com.settlement.system.common.exception.ServiceException;
import com.settlement.system.model.entity.common.CommonPlugIn;
import com.settlement.system.model.entity.common.TblQueryFieldConfig;
import com.settlement.system.reply.ObjectDataResponse;
import com.settlement.system.common.util.common.SystemUserUtil;
import com.settlement.system.service.ITblQueryFieldConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import jakarta.annotation.Resource;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.util.stream.Collectors.groupingBy;

/**
 * 联表查询字段配置表 服务实现类
 * @author xiaochuan
 * @since 2022-01-13
 */
@Slf4j
@Service
public class TblQueryFieldConfigServiceImpl extends BaseServiceImpl implements ITblQueryFieldConfigService {

    private static final Pattern COMPILE_COLUMN = Pattern.compile("[\\u4e00-\\u9fa5\\-A-Za-z_0-9|\\/]{1,}");

    @Resource
    private TblQueryFieldConfigMapper tblQueryFieldConfigMapper;

    @Override
    public BaseMapper init() {
        return tblQueryFieldConfigMapper;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void refresh(Map<String, Object> model) throws ServiceException {
        try {
            tblQueryFieldConfigMapper.clear(model);

            List<TblQueryFieldConfig> fieldConfigs = tblQueryFieldConfigMapper.selectOriginFieldList(model);

            Map<String, List<TblQueryFieldConfig>> collect = fieldConfigs.stream().collect(groupingBy(s -> s.getTableNameCn()));
            for (Map.Entry<String, List<TblQueryFieldConfig>> stringListEntry : collect.entrySet()) {
                List<TblQueryFieldConfig> value = stringListEntry.getValue();
                List<String> keyList = new ArrayList<>();
                for (TblQueryFieldConfig fieldConfig : value) {
                    String columnNameCn = fieldConfig.getColumnNameCn();

                    int i = columnNameCn.indexOf(" ");
                    if(i!=-1){
                        columnNameCn = columnNameCn.substring(0,i);
                    }

                    if (StrUtil.containsAny(columnNameCn, "、", ",", "，", "(", "（", "）", ")", ":", "：")) {
                        if ((StrUtil.containsAny(columnNameCn, "(", "（", "）", ")") &&
                                StrUtil.containsAny(columnNameCn, "、", ",", "，"))
                                ||
                                (!StrUtil.containsAny(columnNameCn, "(", "（", "）", ")") &&
                                        StrUtil.containsAny(columnNameCn, "、", ",", "，", ":", "："))
                        ) {
                            Matcher matcherColumn = COMPILE_COLUMN.matcher(columnNameCn);
                            if (matcherColumn.find()) {
                                columnNameCn = matcherColumn.group();
                                System.out.println(columnNameCn);
                            } else {
                                log.info("字段{}匹配失败", columnNameCn);
                            }
                        }
                    }


                    if(columnNameCn.length()>50){
                        columnNameCn = columnNameCn.substring(0,50);
                    }

                    while (keyList.contains(columnNameCn)){
                        columnNameCn += "_";
                    }
                    keyList.add(columnNameCn);

                    fieldConfig.setColumnNameCn(columnNameCn);
                    SystemUserUtil.setDefualt(fieldConfig);
                }
            }
            int totalCount = fieldConfigs.size();
            int pageSize = 100;
            int totalPage = PageUtil.totalPage(totalCount, pageSize);
            for (int i = 1; i <= totalPage; i++) {
                int start = pageSize * (i - 1);
                int end = start + pageSize;
                if (end > totalCount) {
                    end = totalCount;
                }
                List<TblQueryFieldConfig> tblQueryFieldConfigs = fieldConfigs.subList(start, end);
                tblQueryFieldConfigMapper.batchAdd(tblQueryFieldConfigs);
            }

        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            throw new ServiceException("刷新异常", ex);
        }
    }

    @Override
    public TblQueryFieldConfig getByTableNameCnAndColumnNameCn(TblQueryFieldConfig tblQueryFieldConfig) {
        return tblQueryFieldConfigMapper.getDataBaseColumnNameByModel(tblQueryFieldConfig);
    }

    @Override
    public ObjectDataResponse pullColumnNameList(Map<String, Object> model) {
        Map<String, Object> resultMap = new HashMap<String, Object>(16);
        try {
            List<CommonPlugIn> commonPlugIns = tblQueryFieldConfigMapper.pullColumnNameList(model);
            removeUndisplayedList(commonPlugIns);
            resultMap.put("rows", commonPlugIns);
            return new ObjectDataResponse<Map>(resultMap, ReturnStatusEnum.REQUEST_SUCCESS);
        } catch (Exception e) {
            log.error("获取表名对应的字段名称列表异常", e);
            return new ObjectDataResponse<Map>(null, ReturnStatusEnum.REQUEST_ABNORMAL);
        }
    }

    private void removeUndisplayedList(List<CommonPlugIn> commonPlugIns){
        String[] nameList = new String[]{
                "统一账单明细.NC_渠道",
                "统一账单明细.NC_店铺名称",
                "统一账单明细.NC_店铺编码",
                "统一账单明细.NC_供应商档案",
                "统一账单明细.NC_客户档案",
                "统一账单明细.NC_虚拟账户",
                "统一账单明细.NC_部门编码",
                "统一账单明细.NC_收费项目",
                "统一账单明细.是否资金账户数据",
                "统一账单明细.活动ID",
                "统一账单明细.爱库存_档期名称",
                "统一账单明细.爱库存_主档期名称",
                "统一账单明细.爱库存_数量",
                "统一账单明细.爱库存_售后服务单/AD单号",

                "统一账单明细.登陆账号",
                "统一账单明细.线下打款账号",
                "统一账单明细.LOGIN_ACCOUNT",

                "统一账单明细.爱库存_对账单类型",
                "统一账单明细.AKC_VERIFY_BILL_TYPE"

        };
        List<String> list = Arrays.asList(nameList);

        int index = 0;
        while (true) {
            if(index > commonPlugIns.size()-1) {
                break;
            }
            CommonPlugIn commonPlugIn = commonPlugIns.get(index);

            if(commonPlugIn.getName().contains("统一账单明细.") && list.contains(commonPlugIn.getName())) {
                System.out.println(commonPlugIn.getName());
                commonPlugIns.remove(index);
            }else {
                index++;
            }
        }

    }

}

